#include "tempdefine.h"



// 根据先序和中序遍历构建二叉树
BinLinkTree buildTree(char *preorder, char *inorder, int start, int end)
{
    static int preIndex = 0; // 用于记录先序遍历的当前索引

    if (start > end)
    {
        return NULL;
    }

    // 创建当前结点
    BLNode *root = (BLNode *)malloc(sizeof(BLNode));
    root->data = preorder[preIndex++];
    root->lchild = NULL;
    root->rchild = NULL;

    // 如果子树中只有一个结点，则返回该结点
    if (start == end)
    {
        return root;
    }

    // 在中序遍历数组中找到根节点的索引
    int inIndex;
    for (int i = start; i <= end; i++)
    {
        if (inorder[i] == root->data)
        {
            inIndex = i;
            break;
        }
    }

    // 递归构建左子树和右子树
    root->lchild = buildTree(preorder, inorder, start, inIndex - 1);
    root->rchild = buildTree(preorder, inorder, inIndex + 1, end);

    return root;
}

int main()
{
    // char preorder[] = "abdec";
    // char inorder[] = "dbcae"; 
    // debca  // 4526731
    char preorder[] = "1245367";
    char inorder[] = "4251637";

    int size = strlen(preorder);

    BinLinkTree root = buildTree(preorder, inorder, 0, size - 1);
    printf("postorder result: ");
    postOrder(root);
    printf("\n");
    return 0;
}